package fatworm.storage.file;

import java.nio.*;

import fatworm.server.*;

/**
 * The contents of a disk block in memory. A page is treated as an array of
 * BLOCK_SIZE bytes. There are methods to get/set values into this array, and to
 * read/write the contents of this array to a disk block.
 * 
 * For an example of how to use Page and {@link Block} objects, consider the
 * following code fragment. The first portion increments the integer at offset
 * 792 of block 6 of file junk. The second portion stores the string "hello" at
 * offset 20 of a page, and then appends it to a new block of the file. It then
 * reads that block into another page and extracts the value "hello" into
 * variable s.
 * 
 * <pre>
 * Page p1 = new Page();
 * Block blk = new Block(&quot;junk&quot;, 6);
 * p1.read(blk);
 * int n = p1.getInt(792);
 * p1.setInt(792, n + 1);
 * p1.write(blk);
 * Page p2 = new Page();
 * p2.setString(20, &quot;hello&quot;);
 * blk = p2.append(&quot;junk&quot;);
 * Page p3 = new Page();
 * p3.read(blk);
 * String s = p3.getString(20);
 * </pre>
 * 
 * @author Edward Sciore
 */
public class Page
{
    public static final int BLOCK_SIZE = 4048;
    // TODO FOR TEST
    private ByteBuffer contents = ByteBuffer.allocateDirect(BLOCK_SIZE);
    private FileMgr filemgr = Fatworm.fileMgr;

    public Page()
    {
    }
    public synchronized void read(Block blk)
    {
        filemgr.read(blk, contents);
    }
    public synchronized void write(Block blk)
    {
        filemgr.write(blk, contents);
    }
    public synchronized Block append(String filename)
    {
        return filemgr.append(filename, contents);
    }
    public synchronized int getInt(int offset)
    {
        contents.position(offset);
        return contents.getInt();
    }
    public synchronized void setInt(int offset, int val)
    {
        contents.position(offset);
        contents.putInt(val);
    }
    public synchronized byte[] getBytes(int offset, int len)
    {
        contents.position(offset);
        byte[] byteval = new byte[len];
        contents.get(byteval);
        return byteval;
    }
    public synchronized void setBytes(int offset, byte[] val)
    {
        contents.position(offset);
        contents.put(val);
    }
}
